package com.qf.commons.web.resp;

import com.qf.data.r.Codes;
import com.qf.data.r.R;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * description: 响应数据的处理器 - 用来正确的设置Http响应码
 * author: Ken
 * 公众号：Java架构栈
 */
@RestControllerAdvice
public class ResponseDataHandler implements ResponseBodyAdvice<R> {

    /**
     * 只处理返回结果为R对象的请求
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return returnType.getMethod().getReturnType() == R.class;
    }

    /**
     * 基于R对象正确的设置Http响应码
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public R beforeBodyWrite(R body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        //是否为成功的响应码
        if (body != null && body.getCode().intValue() != Codes.SUCC.getCode()) {
            //说明当前是非成功的响应
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return body;
    }
}
